﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Admin.NET.Core;

namespace Admin.NET.Application
{
    /// <summary>
    /// 库位信息服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsPlace", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsPlaceService : IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;
        private readonly IRepository<WmsArea> _wmsAreaRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        public WmsPlaceService(
            IRepository<WmsArea> wmsAreaRep,
            IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep
        )
        {
            _wmsAreaRep = wmsAreaRep;
            _wmsPlaceRep = wmsPlaceRep;
        }

        /// <summary>
        /// 分页查询库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsPlaceOutput>> Page([FromQuery] WmsPlaceSearch input)
        {
            var wmsPlaces = await _wmsPlaceRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.Placecode), u => EF.Functions.Like(u.PlaceCode, $"%{input.Placecode.Trim()}%"))
                .Where(input.Placestatus != null, u => u.PlaceStatus == input.Placestatus)
                .Where(input.Areaid > 0, u => u.AreaId == input.Areaid)
                .Where(input.Rowno != null, u => u.RowNo == input.Rowno)
                .Where(input.Columnno != null, u => u.ColumnNo == input.Columnno)
                .Where(input.Layerno != null, u => u.LayerNo == input.Layerno)
                .Where(input.Aisle != null, u => u.Aisle == input.Aisle)
                .Where(input.Islock != null, u => u.Islock == input.Islock)
                .OrderBy(PageInputOrder.OrderBuilder<WmsPlaceSearch>(input))
                .ProjectToType<WmsPlaceOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsPlaces;
        }

        /// <summary>
        /// 增加库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[HttpPost("add")]
        //public async Task Add(AddWmsPlaceInput input)
        //{
        //    //获取库区信息
        //    var wmsArea = await _wmsAreaRep.FirstOrDefaultAsync(u => u.Id == input.Areaid);
        //    if (wmsArea.AreaType == AreaType.LITIKU)
        //    {
        //        var wmsPlace = input.Adapt<WmsPlace>();
        //        for (int a = 1; a == 1; a++)
        //        {
        //            for (int t = 1; t <= wmsPlace.RowNo; t++)   //循环排
        //            {
        //                for (int i = 1; i <= wmsPlace.ColumnNo; i++)   //循环列
        //                {
        //                    for (int j = 1; j <= wmsPlace.LayerNo; j++)  //循环层
        //                    {
        //                        var model = new WmsPlace();
        //                        model.PlaceStatus = PlaceStatus.KONGXIAN;
        //                        model.AreaId = wmsPlace.AreaId;
        //                        model.RowNo = t;
        //                        model.ColumnNo = i;
        //                        model.LayerNo = j;
        //                        model.DeepcellNo = 1;
        //                        model.Aisle = a;
        //                        model.Islock = YesOrNot.N;
        //                        model.Length = new decimal(1.2);
        //                        model.Width = new decimal(1.5);
        //                        model.Height = new decimal(1.8);
        //                        model.MaxWeight = new decimal(2.8);
        //                        model.HeightLevel = Heightlevel.DI;
        //                        model.Priority = 0;
        //                        model.AgvCode = "";
        //                        model.PlaceCode = String.Format("{0}{1}{2}{3}{4}", wmsArea.AreaDesc, a.ToString("00"), t.ToString("00"), i.ToString("00"), j.ToString("00"));
        //                        var isExit = await _wmsPlaceRep.AnyAsync(n => n.PlaceCode == model.PlaceCode);
        //                        if (!isExit) await _wmsPlaceRep.InsertAsync(model);
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    else
        //    {
        //        var wmsPlace = input.Adapt<WmsPlace>();
        //        for (int t = 1; t <= wmsPlace.RowNo; t++)   //循环排
        //        {
        //            for (int i = 1; i <= wmsPlace.ColumnNo; i++)   //循环列
        //            {
        //                for (int j = 1; j <= wmsPlace.LayerNo; j++)  //循环层
        //                {
        //                    var model = new WmsPlace();
        //                    model.PlaceStatus = PlaceStatus.KONGXIAN;
        //                    model.AreaId = wmsPlace.AreaId;
        //                    model.RowNo = t;
        //                    model.ColumnNo = i;
        //                    model.LayerNo = j;
        //                    model.DeepcellNo = 1;
        //                    model.Aisle = wmsPlace.Aisle;
        //                    model.Islock = YesOrNot.N;
        //                    model.Length = new decimal(1.2);
        //                    model.Width = new decimal(1.5);
        //                    model.Height = new decimal(1.8);
        //                    model.MaxWeight = new decimal(2.8);
        //                    model.HeightLevel = Heightlevel.DI;
        //                    model.Priority = 0;
        //                    model.AgvCode = "";
        //                    model.PlaceCode = String.Format("{0}{1}{2}{3}", wmsArea.AreaDesc, t.ToString("00"), i.ToString("00"), j.ToString("00"));
        //                    var isExit = await _wmsPlaceRep.AnyAsync(n => n.PlaceCode == model.PlaceCode);
        //                    if (!isExit) await _wmsPlaceRep.InsertAsync(model);
        //                }
        //            }
        //        }
        //    }

        //}

        /// <summary>
        /// 增加库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task AddNew(AddWmsPlaceInput input)
        {
            var isExit = await _wmsPlaceRep.AnyAsync(n => n.PlaceCode == input.Placecode);
            if (isExit) throw Oops.Oh("存在的相同的库位编码！");
            var wmsPlace = input.Adapt<WmsPlace>();
            wmsPlace.AgvCode = "Y/N";
            wmsPlace.PlaceStatus = PlaceStatus.KONGXIAN;
            wmsPlace.Islock = YesOrNot.N;
            wmsPlace.EmptyContainer = YesOrNot.N;
            if (input.Heightlevel==0) {
                wmsPlace.HeightLevel = Heightlevel.DI;
            }
            await _wmsPlaceRep.InsertAsync(wmsPlace);
        }

        /// <summary>
        /// 删除库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsPlaceInput input)
        {
            var wmsPlace = await _wmsPlaceRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsPlaceRep.DeleteAsync(wmsPlace);
        }

        /// <summary>
        /// 批量锁定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("MoreLock")]
        public async Task MoreLock(MoreLockInput input)
        {
            if (input.Id.Count <= 0) throw Oops.Oh("id不能为空！");
            foreach (var item in input.Id)
            {
                var wmsPlace = await _wmsPlaceRep.FirstOrDefaultAsync(u => u.Id == item);
                if (wmsPlace == null) throw Oops.Oh("库位信息不存在!");
                wmsPlace.Islock = YesOrNot.Y;
                await _wmsPlaceRep.UpdateAsync(wmsPlace, ignoreNullValues: true);
            }
        }

        /// <summary>
        /// 批量解锁
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("MoreUnlock")]
        public async Task MoreUnlock(MoreLockInput input)
        {
            if (input.Id.Count <= 0) throw Oops.Oh("id不能为空！");
            foreach (var item in input.Id)
            {
                var wmsPlace = await _wmsPlaceRep.FirstOrDefaultAsync(u => u.Id == item);
                if (wmsPlace == null) throw Oops.Oh("库位信息不存在!");
                wmsPlace.Islock = YesOrNot.N;
                await _wmsPlaceRep.UpdateAsync(wmsPlace, ignoreNullValues: true);
            }
        }

        /// <summary>
        /// 更新库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsPlaceInput input)
        {
            var isExist = await _wmsPlaceRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsPlace = input.Adapt<WmsPlace>();
            await _wmsPlaceRep.UpdateAsync(wmsPlace, ignoreNullValues: true);
        }

        /// <summary>
        /// 获取库位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsPlaceOutput> Get([FromQuery] QueryeWmsPlaceInput input)
        {
            return (await _wmsPlaceRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsPlaceOutput>();
        }

        /// <summary>
        /// 获取库位信息列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsPlaceOutput>> List([FromQuery] WmsPlaceInput input)
        {
            return await _wmsPlaceRep.DetachedEntities.ProjectToType<WmsPlaceOutput>().ToListAsync();
        }

        /// <summary>
        /// 获取WmsArea列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("fkWmsArea")]
        public async Task<dynamic> FkWmsAreaList()
        {
            var list = await _wmsAreaRep.DetachedEntities.ToListAsync();
            return list.Select(e => new { Code = e.Id, Name = e.AreaName });
        }

        /// <summary>
        /// 获取熟化库巷道
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetFAisle")]
        public async Task<object> GetFAisle()
        {
            var area = await _wmsAreaRep.FirstOrDefaultAsync(n => n.AreaStatus == CommonStatus.ENABLE && n.WorkShopType == LesWorkShopType.FAPAOCHEJIAN && n.AreaType == AreaType.LITIKU);
            var objList = await _wmsPlaceRep.Where(n => n.AreaId == area.Id).OrderBy(n => n.Aisle).Select(n => n.Aisle).Distinct().ToArrayAsync();
            for (int i = 0; i < objList.Length - 1; i++)
            {
                for (int j = 0; j < objList.Length - 1; j++)
                {
                    int k = j + 1;
                    if (objList[j] > objList[k])
                    {
                        var temp = objList[k];
                        objList[k] = objList[j];
                        objList[j] = temp;
                    }
                }
            }
            return objList;
        }
    }

}
